#include "viewmain.h"

#include <iostream>
#include <ncurses.h>
#include <QMediaPlayer>

#include "viewprocess.h"

MainView::MainView()
{

    m_window = newwin(0, 0.6 * COLS, 0, 0);
    m_cols = 0.6 * COLS;
    m_lines = LINES;

}

void MainView::show()
{
    bool flag = true;
    while (flag) {
        mvwprintw(m_window, 1, 0.5 * m_cols - 13, "欢迎来到《单词快打》，冲！");
        keypad(m_window,TRUE);    //接受快捷键
        box(m_window, '+', '*');
        wrefresh(m_window);
        drawMenu(10,0.5*m_cols - 10);

        flag = listen();
        wrefresh(m_window);
    }


}
bool MainView::listen()
{
    int selected = scroll_menu(m_menuItems, 5);
    if(selected == 4){
        return false;
    }
    run(selected);
    delete_menu(m_menuItems,9);
    return true;
}

void MainView::run(int menuId)
{
    Process process(m_lines, m_cols);

    if(menuId == 0) {
        process.rush();
    }
    else if(menuId == 1) {
        process.config();

    }
    else if(menuId == 2) {
        process.load();
    }
    else if(menuId == 3) {

    }
}


void MainView::drawMenu(int startLine, int startCol)
{

    m_menuItems=(WINDOW **)malloc(6*sizeof(WINDOW *));

    m_menuItems[0]=newwin(10,19,startLine,startCol);
    wbkgd(m_menuItems[0],COLOR_PAIR(2));
    box(m_menuItems[0],ACS_VLINE,ACS_HLINE);

    m_menuItems[1]=subwin(m_menuItems[0],1,17,startLine+1,startCol+1);
    wprintw(m_menuItems[1],"刷单词");
    m_menuItems[2]=subwin(m_menuItems[0],1,17,startLine+2,startCol+1);
    wprintw(m_menuItems[2],"更改计划");
    m_menuItems[3]=subwin(m_menuItems[0],1,17,startLine+3,startCol+1);
    wprintw(m_menuItems[3],"自定义词汇");
    m_menuItems[4]=subwin(m_menuItems[0],1,17,startLine+4,startCol+1);
    wprintw(m_menuItems[4],"设置");
    m_menuItems[5]=subwin(m_menuItems[0],1,17,startLine+5,startCol+1);
    wprintw(m_menuItems[5],"退出");


    wbkgd(m_menuItems[1],COLOR_PAIR(1));
    wrefresh(m_menuItems[0]);
}
void MainView::delete_menu(WINDOW **items,int count)
{
    int i;
    for (i=0;i<count;i++)
        delwin(items[i]);
    free(items);
}
int MainView::scroll_menu(WINDOW **items,int count)
{
    int key;
    int selected=0;
    while (1) {
        key=wgetch(m_window);
        if (key==KEY_DOWN || key==KEY_UP) {
            wbkgd(items[selected+1],COLOR_PAIR(2));
            wnoutrefresh(items[selected+1]);
            if (key==KEY_DOWN) {
                selected=(selected+1) % count;
            } else {
                selected=(selected+count-1) % count;
            }
            wbkgd(items[selected+1],COLOR_PAIR(1));
            wnoutrefresh(items[selected+1]);
            doupdate();
        }
        else if (key==ENTER) {
            return selected;
        }
    }
}
